<template>
  <div v-if="comments.length > 0">
    <div>全部评论({{ comments.length }})</div>
    <div class="comment-list">
      <div class="comment-item" v-for="(comment,index) in comments" :key="index">
      <div class="comment-user-info">
        <v-avatar :size="50">
          <v-img :src="userInfo ? apiFileGet(comment.user.avatar) : '/logo.png'"></v-img>
        </v-avatar>
        <div class="user-details">
          <span class="user-nickname">{{ comment.user.nickName }}</span>
          <span class="user-date">{{ comment.gmtUpdated }}</span>
        </div>
        <!-- 删除按钮 -->
        <button v-if="comment.userId == userInfo.id" class="delete-button" @click="deleteComment(comment.id)">
          <v-icon>
            mdi-trash-can-outline
          </v-icon>
        </button>
      </div>
      <div class="comment-content">{{ comment.content }}</div>
    </div>
    </div>
  </div>
  <div v-else style="text-align: center;line-height: 50">
    {{ noDataMsg }}
  </div>
  <!-- 固定的评论输入框和提交按钮部分 -->
  <div class="comment-input-container" :class="{ 'expanded': comment.length > 15 }">
    <textarea v-model="comment" placeholder="留下你的精彩评论吧" @keydown="handleKeyDown" @input="handleInput" ref="commentInput">
    </textarea>
    <button v-show="comment" class="send-button" @click="submitComment">
      <v-icon :size="30">mdi-arrow-up-bold-circle-outline</v-icon>
    </button>
  </div>
  <!-- 用户操作提示消息 -->
  <v-snackbar v-model="snackbar.show" :color="snackbar.color">
    {{ snackbar.text }}
    <template v-slot:actions>
      <v-btn color="blue" variant="text" @click="snackbar.show = false">
        了解
      </v-btn>
    </template>
  </v-snackbar>

</template>

<script setup>
import { onMounted, ref, watch,onUnmounted } from "vue";
import { apiAddcomment, apiGetComment, apiDeleteComment} from "../../apis/videoComment"
import { apiFileGet } from "../../apis/file";
import { apiGetUserInfo } from "../../apis/user/user";
import { useUserStore } from "../../stores";
// 接收父组件传入的数据
const props = defineProps({
  // 视频信息
  videoInfo: {
    type: Object,
    default: null,
  },
  noDataMsg: {
    type: String,
    default: "未评论",
  },
});
const userStore = useUserStore();
const userInfo = ref(null);
// 获取用户信息
const getUserInfo = () => {
  apiGetUserInfo(userStore.$state.lookId).then(({ data }) => {
    if (!data.state) {
      return;
    }
    userInfo.value = data.data;
  });
};
// 评论集合
const comments = ref([]);
// 当前分页
const currentPage = ref({
  page: 1,
  limit: 10
});
// 获取评论
const getComments = () => {
  apiGetComment(props.videoInfo.id,currentPage.value.page,currentPage.value.limit).then((data) => {
    if(data.data.data){
      if (currentPage.value.page === 1){
        comments.value = [];
      }
      comments.value = comments.value.concat(data.data.data);
    }
  }); 
};
// 提示框信息
const snackbar = ref({
    show: false,
    text: ""
})
// 输入框中的评论值
const comment = ref("");
// 提交评论
const submitComment = () =>{
  apiAddcomment(props.videoInfo.id,comment.value).then((data)=>{
    snackbar.value = {
        show: data.state,
        text: data.message
    };
    comment.value = "";
    getComments();
  })
}
// 删除评论
const deleteComment = (commentId) => {
  apiDeleteComment(commentId).then((data)=>{
    snackbar.value = {
        show: data.state,
        text: data.message
    };
    getComments();
  })
}
// 监听滚动事件
const listenScroll = () => {
  //变量scrollTop是滚动条滚动时，距离顶部的距离
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  //变量windowHeight是可视区的高度
  var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
  //变量scrollHeight是滚动条的总高度
  var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
  //滚动条到底部的条件
  let sum = scrollHeight - ((scrollTop + windowHeight))
  if (sum < 150 && sum > -1) {
    // 自增页码
    currentPage.value.page++
    // 查询评论
    getComments()
  }
}

// 处理按键事件
const handleKeyDown = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault(); // 阻止默认的换行行为
    submitComment(); // 触发发布评论操作
  }
}
const commentInput = ref(null)
// 处理输入事件
const handleInput = () => {
  if (commentInput.value) {
     // 记录当前滚动位置
     const scrollTop = commentInput.value.scrollTop;
    // 重置输入框高度
    commentInput.value.style.height = 'auto';
    // 设置输入框高度为滚动高度
    commentInput.value.style.height = commentInput.value.scrollHeight + 'px';

    // 限制最大行数，超过 13 行显示滚动条
    const maxHeight = 260; // 13 行 * 20px 行高
    if (commentInput.value.scrollHeight > maxHeight) {
      commentInput.value.style.height = maxHeight + 'px';
      commentInput.value.style.overflowY = 'auto';
    } else {
      commentInput.value.style.overflowY = 'hidden';
    }

     // 恢复滚动位置
     commentInput.value.scrollTop = scrollTop;
  }
};

const isLoading = ref(false);
watch(props.videoInfo,() =>{
  if (!isLoading.value) {
    isLoading.value = true;
    currentPage.value.page = 1
    getComments();
    // 加载完成后重置标志位
    setTimeout(() => {
      isLoading.value = false;
    }, 1000);
  }
},{
    deep: true,
})

onMounted(() => {
  getUserInfo();
  getComments();
  // 添加窗口滚动事件监听器
  window.addEventListener('scroll', listenScroll);
})

onUnmounted(() => {
  // 卸载窗口滚动事件监听器
  window.removeEventListener('scroll', listenScroll);
})

</script>

<style scoped>
.comment-list {
  padding-bottom: 30px; /* 为底部输入框留出空间 */
}
/* 每个评论项样式 */
.comment-item {
  position: relative;
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
  padding: 10px;
}

/* 评论者信息样式 */
.comment-user-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.user-details {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
}

.user-nickname {
  color: white;
  font-weight: bold;
}

.user-date {
  color: gray;
  font-size: 0.9em;
}

/* 删除按钮样式 */
.delete-button {
  position: absolute; /* 绝对定位 */
  top: 10px; /* 距离顶部 10px */
  right: 10px; /* 距离右侧 10px */
  background-color: transparent;
  border: none;
  color: gray;
  cursor: pointer;
}
.delete-button:hover {
  color: white;
}
.delete-button::after{
  content: "删除评论";
  position: absolute;
  top: 30px;
  left: -20px;
  width: 100px;
  height: 40px;
  transform: translateX(-50%);
  background-color: rgb(63, 62, 62);
  color: white;
  padding: 4px 8px;
  border-radius: 10px;
  font-size: 15px;
  white-space: nowrap;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0; /* 默认透明度为 0，即隐藏 */
  pointer-events: none; /* 防止提示框影响鼠标事件 */
  transition: opacity 0.4s ease; /* 添加过渡效果 */
}
/* 鼠标悬停在删除按钮上时提示框的样式 */
.delete-button:hover::after {
  opacity: 1; /* 透明度变为 1，即显示 */
}

/* 评论内容样式 */
.comment-content {
  color: white;
  line-height: 1.4; /* 可根据需求调整行高 */
}

/* 输入框样式 */
.comment-input-container {
  position: fixed;
  bottom: 15px;
  left: 15px;
  right: 15px;
  display: flex;
  align-items: center;
  background-color: #4b4b49fa;
  border-radius: 25px;
  padding: 8px 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.comment-input-container.expanded {
  flex-direction: column;
  align-items: flex-end;
}

.comment-input-container textarea {
  width: 100%;
  border: none;
  background-color: transparent;
  color: white;
  resize: none;
  outline: none;
  font-size: 16px;
  line-height: 20px;
  min-height: 20px;
  max-height: 260px;
  overflow-y: auto;
}

.comment-input-container textarea::placeholder {
  color: white;
  opacity: 0.7;
}

.send-button {
  color: white;
  border: none;
  padding: 3px 5px;
  margin-left: 10px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.comment-input-container.expanded .send-button {
  align-self: flex-end;
  margin-top: 8px;
  margin-right: 0;
}

.send-button:hover {
  color: red;
}
</style>